package address.service.impl;

import address.mapper.AddressMapper;
import address.service.IAddressService;
import lombok.extern.slf4j.Slf4j;
import common.model.user.Address;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class AddressServiceImpl implements IAddressService {

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> list(Long userId) {
        //查询所有地址
        List<Address> list = addressMapper.list(userId);
        return list;
    }

    @Override
    public Address getDefault(Long uid) {
        //查询默认地址
        Address address = addressMapper.getDefault(uid);
        return address;
    }

    @Override
    public void create(Address address) {
        System.out.println(address);
        //查询当前用户是否有默认地址
        Address result = addressMapper.getDefault(address.getUid());
        if (result == null) {
            //没有默认地址，设置为默认地址
            address.setDefault(true);
        }
        //判断是否为默认地址
        if (address.isDefault()) {
            //如果是默认地址，将所有地址设置为非默认地址
            addressMapper.clearDefault(address.getUid());
        }
        //新增地址
        addressMapper.create(address);
    }

    @Override
    @Transactional
    public void update(Address address) {
        System.out.println(address);
        //查询当前用户是否有默认地址
        Address result = addressMapper.getDefault(address.getUid());
        if (result == null) {
            //没有默认地址，设置为默认地址
            address.setDefault(true);
        }
        //判断是否为默认地址
        if (address.isDefault()) {
            if (address.isDefault()) {
                log.info("Setting address {} as default for user {}", address.getId(), address.getUid());
                addressMapper.clearDefault(address.getUid());
                log.info("Cleared previous default addresses for user {}", address.getUid());
            }
        }
        //修改地址
        addressMapper.update(address);
    }

    @Override
    public void delete(Long id) {
        //删除地址
        addressMapper.delete(id);
    }
}
